package com.ld.zxw.init;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.lucene.store.FSDirectory;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.ld.zxw.Analyzer.AnalyzerPlugin;
import com.ld.zxw.Documents.Documents;
import com.ld.zxw.add.AddIndex;
import com.ld.zxw.config.Config;
import com.ld.zxw.delete.DeleteIndex;
import com.ld.zxw.query.QueryIndex;
import com.ld.zxw.update.UpdateIndex;
@SuppressWarnings("all")
public class Init {
	
	private Config config  = null;
	private String AnalyzerTypes = null; 
	private String core;
	public Init(Config config,String core,String analyzerTypes) {
		this.config = config;
		this.AnalyzerTypes = analyzerTypes;
		this.core = core;
	}
	
	/**
	 * 基础配置整合
	 * @throws IOException
	 */
	public void start() throws IOException{
		String lucene_core = config.getLucene_path()+this.core;
		config.setAnalyzer(new AnalyzerPlugin(this.AnalyzerTypes).getAnalyzer());
		Path path=Paths.get(lucene_core+"/data");
		config.setDirectory(FSDirectory.open(path));
		config.setXmlDem(xmlDem(lucene_core+"/conf/config.xml",null));
		config.setIsQuery(xmlDem(lucene_core+"/conf/config.xml","1"));
		
		//赋值
		AddIndex.config = this.config;
		DeleteIndex.config = this.config;
		Documents.config = this.config;
		QueryIndex.config = this.config;
		UpdateIndex.config = this.config;
	}
	
	/**
	 * 解析配置文件
	 * @param conf
	 * @return
	 */
	public static List<Map<String, String>> xmlDem(String conf,String type){
		SAXReader saxReader = new SAXReader();
		File file = new File(conf);
		org.dom4j.Document read;
		List<Map<String, String>> list=new ArrayList<>();
		try {
			read = saxReader.read(file);
			Element rootElement = read.getRootElement();
			List<Element> elements = rootElement.elements();
			for (Element element : elements) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("name", element.attributeValue("name"));
				map.put("type", element.attributeValue("type"));
				map.put("isSort", element.attributeValue("isSort"));
				String isQuery = element.attributeValue("isQuery");
				if(type == null){
					map.put("isQuery", element.attributeValue("isQuery"));
				}else{
					if(type.equals("1") && isQuery.equals("y")){//过滤要查询的数据
						map.put("isQuery", element.attributeValue("isQuery"));
					}else{
						continue;
					}
				}
				list.add(map);
			}
			return list;
		} catch (DocumentException e) {
			return null;
		}
	}
	
}
